package com.aoxon.cargo.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.Picture;
import com.aoxon.cargo.bean.Supplier;
import com.aoxon.cargo.cache.FileManager;
import com.aoxon.cargo.component.MyCallBack;
import com.aoxon.cargo.component.MyListDialog;
import com.aoxon.cargo.component.MyProgressDialog;
import com.aoxon.cargo.loader.FileLoader;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.FileUpLoadService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.RevampStoreService;
import com.aoxon.cargo.shared.SupIndexShared;
import com.aoxon.cargo.state.DataState;
import com.aoxon.cargo.state.MyReturnState;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.EnvironmentUtil;
import com.aoxon.cargo.util.ImageUtil;
import com.aoxon.cargo.util.ToastUtil;
import com.google.gson.JsonSyntaxException;

public class SupFillInfo3Activity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {
	private ImageView ivLogo, ivAddLogo, ivReturn;
	private TextView tvNext, tvJustNow, tvTitle;

	private boolean update;
	private final int NEXT = 0;
	private final int JUST_NOW = 1;
	private int toIntent;
	private FileLoader fileLoader;
	private Supplier supplier;
	private Picture logo = new Picture();
	private MyListDialog myListDialog;
	private FileManager imageManager = new FileManager();
	private FileUpLoadService fileUpLoadService = new FileUpLoadService();
	private RevampStoreService revampStoreService = (RevampStoreService) MyServiceFactory
			.getInstance(MyServiceFactory.REVAMP_STORE);
	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);
	private MyProgressDialog myProgressDialog;
	private File file;
	String tag = "SupFillInfo3Activity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setup();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		update = true;
		Log.v(tag, "requestCode" + requestCode);
		Bitmap bitmap = null;
		String path = null;
		if (resultCode == RESULT_OK) {

			if (requestCode == MyStateUtil.CAMERA_for_LOGO) {
				// FileInputStream fis;
				try {
					// fis = new FileInputStream(file);
					// bitmap = BitmapFactory.decodeStream(fis);
					bitmap = ImageUtil.getImageBitmap(file.getPath(), 200, 200);
					Log.v(tag, " 图片 width" + bitmap.getWidth());
					file = null;
					// fis=null;
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (bitmap.getWidth() < 200 || bitmap.getHeight() < 200) {
					ToastUtil.show(SupFillInfo3Activity.this,
							"图片分辨率不要小于200x200");
					Log.v(tag, " 图片太小 不要小于200x200 ");

				} else {
					path = imageManager.saveBitmap(bitmap);
					logo.setPictureUrl(path);
					logo.setPictureType(MyReturnState.LOGO_TYPE);
					logo.setPictureState(DataState.INITIAL);
					ivLogo.setImageBitmap(ImageUtil.imageCropToSquare(bitmap));
					bitmap = null;
				}

			} else {// 文件中选图片

				try {
					path = ImageUtil.getAbsoluteImagePath(data.getData(), this);
					logo.setPictureUrl(path);
					bitmap = ImageUtil.getImageBitmap(path, 200, 200);
					if (bitmap.getWidth() < 200 || bitmap.getHeight() < 200) {
						ToastUtil.show(SupFillInfo3Activity.this,
								"图片分辨率不要小于200x200");
						Log.v(tag, " 图片太小 不要小于200x200 ");
					} else {
						logo.setPictureType(MyReturnState.LOGO_TYPE);
						logo.setPictureState(DataState.INITIAL);
						ivLogo.setImageBitmap(ImageUtil.imageCropToSquare(bitmap));
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.v(tag, " 图片太小 ");
					e.printStackTrace();
				}

			}
		}
	}

	private void setup() {
		setContentView(R.layout.sup_fill_info3);
		supplier = SupIndexShared.getSupplier();
		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);
		tvNext = (TextView) findViewById(R.id.tvNext_fill_info3);
		tvJustNow = (TextView) findViewById(R.id.tvJustNow_fill_info3);
		ivReturn = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		ivLogo = (ImageView) findViewById(R.id.ivLogo_fill_info3);
		ivAddLogo = (ImageView) findViewById(R.id.ivAddLogo_fill_info3);

		myProgressDialog = new MyProgressDialog(this);
		tvTitle.setText("完善信息-LOGO");
		fileLoader = new FileLoader(200, 200, false);
		myListDialog = new MyListDialog(this);
		if (supplier != null && supplier.getSupLogo() != null) {
			for (int i = 0; i < supplier.getSupLogo().size(); i++) {
				Picture picture = supplier.getSupLogo().get(i);
				if (picture.getPictureState() == DataState.SUCCESS) {
					fileLoader.displayImage(picture.getPictureUrl() + "s.png",
							ivLogo, null, false);
				}
			}
		}
		ivReturn.setOnClickListener(onClick);
		ivAddLogo.setOnClickListener(onClick);
		tvNext.setOnClickListener(onClick);
		tvJustNow.setOnClickListener(onClick);
		normalDataLoader.setOnloadDataListener(this);
		// Log.v( tag , "width " + width);
		// fileLoader = new FileLoader()
	}

	OnClickListener onClick = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.ivAddLogo_fill_info3:
				myListDialog.show("请选择", new String[] { "拍照", "本地文件" },
						new TakePhotoForStoreLogo());
				break;
			case R.id.tvNext_fill_info3:
				toIntent = NEXT;
				if (update) {
					normalDataLoader.load();
				}else{
					commitResult();
				}
				break;
			case R.id.tvJustNow_fill_info3:
				toIntent = JUST_NOW;
				if (update) {
					normalDataLoader.load();
				}else{
					commitResult();
				}
				break;
			case R.id.ivPublicTitleReturn:
				finish();
				break;
			}
		}
	};

	class TakePhotoForStoreLogo implements MyCallBack {
		@Override
		public void callback(String choose) {
			if (choose.equals("拍照")) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				String path = android.os.Environment
						.getExternalStorageDirectory().getAbsolutePath()
						+ "/nahuo/picture/xuan.png";
				file = new File(path);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
				startActivityForResult(intent, MyStateUtil.CAMERA_for_LOGO);
			} else {
				try {
					Intent intent = new Intent(
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(intent, MyStateUtil.FOLDER_for_LOGO);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	private void commitResult(){
		switch(toIntent){
		case NEXT:
			Intent intentNext = new Intent(SupFillInfo3Activity.this,
					SupFillInfo4Activity.class);
			startActivity(intentNext);
			break;
		case JUST_NOW:
			CargoActivity.OPEN_CHOOSE = MyStateUtil.OPEN_MORE;
			Intent intentMore = new Intent(SupFillInfo3Activity.this,
					CargoActivity.class);
			startActivity(intentMore);
			break;
		}
	}
	
	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub
//		ToastUtil.show(SupFillInfo3Activity.this, "正在更新数据");
		myProgressDialog.show("提示", "提交中，请稍候...");
	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub

		// logo在改变时才设置了PictureType
		Log.v(tag, DataUtil.gson.toJson(supplier));
		if (logo.getPictureType() == MyReturnState.LOGO_TYPE) {
			List<Picture> logos = new ArrayList<Picture>();
			GsonBean gsonBean = fileUpLoadService.upLoadPicture(logo
					.getPictureUrl());
			try {
				if (CheckStateUtil.check(gsonBean)) {
					Picture pictureReturn = DataUtil.gson.fromJson(
							gsonBean.getStrJson(), Picture.class);
					logos.add(pictureReturn);
					Log.v("pictrue return ",
							DataUtil.gson.toJson(pictureReturn));
					// 判断上传成功,删除以前的logo
					if (supplier != null) {
						if (supplier.getSupLogo() != null) {
							for (int i = 0; i < supplier.getSupLogo().size(); i++) {
								supplier.getSupLogo().get(i)
										.setPictureState(DataState.DELETE);
							}
							gsonBean = revampStoreService.execute(supplier);
						}
						
						if (CheckStateUtil.check(gsonBean)) {
							if (supplier.getSupLogo() == null) {
								supplier.setSupLogo(logos);
							} else {
								supplier.getSupLogo().set(0, pictureReturn);
							}

							if (EnvironmentUtil.checkNetState(getBaseContext())) {
								supplier.getSupLogo().addAll(logos);
								Log.v(tag, DataUtil.gson.toJson(supplier));
								gsonBean = revampStoreService.execute(supplier);
								try {
									if (CheckStateUtil.check(gsonBean)) {
										SupIndexShared
												.saveSupplierAndKey(DataUtil.gson
														.toJson(supplier));
										msg.what = MyStateUtil.UPLOAD_RESULT;
									}else{
										msg.what = MyStateUtil.UPLOAD_ERROR;
									}
								} catch (Exception e) {
									msg.what = MyStateUtil.UPLOAD_ERROR;
									e.printStackTrace();
								}
							} else {
								msg.what = MyStateUtil.NOT_NET_CONNECTION;
							}
						}
					} else {
						msg.what = MyStateUtil.UPLOAD_ERROR;
					}

					// revampStoreService.execute(supplier);
				}
			} catch (JsonSyntaxException e) {
				// TODO Auto-generated catch block
				msg.what = MyStateUtil.UPLOAD_ERROR;
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				msg.what = MyStateUtil.ERROR_NET_CONNECTION;
				e.printStackTrace();
			}

		}

	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		myProgressDialog.cancle();
		switch (state) {
		case MyStateUtil.UPLOAD_RESULT:
			ToastUtil.show(getBaseContext(), "上传成功");
			break;
		case MyStateUtil.UPLOAD_ERROR:
			ToastUtil.show(getBaseContext(), "上传出错，请重新提交");
			break;
		case MyStateUtil.RETURN_FAIL:
			ToastUtil.show(getBaseContext(), "无对应数据");
			break;
		case MyStateUtil.NOT_NET_CONNECTION:
			ToastUtil.show(getBaseContext(), "无网络连接");
			break;
		case MyStateUtil.ERROR_NET_CONNECTION:
			ToastUtil.show(getBaseContext(), "网络连接异常");
			break;
		default:
			ToastUtil.show(getBaseContext(), "上传出错，请重新提交");
			break;
		
		}
		commitResult();
	}

}
